package com.kaibes.platform.member.db;

import java.time.LocalDate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kaibes.core.base.util.IntegerUtils;
import com.kaibes.orm.core.core.Page;
import com.kaibes.orm.curd.Query;
import com.kaibes.orm.curd.QueryBuilder;
import com.kaibes.orm.curd.SelectBuilder;
import com.kaibes.orm.curd.UpdateBuilder;
import com.kaibes.platform.member.pojo.MemberUpdate;
import com.kaibes.web.api.ResponseServiceImpl;

@Service
public class MemberService extends ResponseServiceImpl<Member>{
    
    @Autowired
    private MemberLevelService memberLevelService;
    
    public Member getByUserId(Integer userId) {
        return get(QueryBuilder.newBuilder().eq("user_id", userId).build());
    }
    
    public Page<Member> pageByNicknameLike(Integer current, Integer size, String search) {
        return getMapper().page(SelectBuilder.newBuilder().addQuery(QueryBuilder.newBuilder().like("username", search).build()).build(), current, size);
    }
    
    public Page<Member> pageByVipId(Integer current, Integer size, int vidId) {
        return getMapper().page(SelectBuilder.newBuilder().addQuery(QueryBuilder.newBuilder().like("vip_id", vidId).build()).build(), current, size);
    }
    
    public Page<Member> pageByLevelId(Integer current, Integer size, int levelId) {
        MemberLevel min = memberLevelService.getById(levelId);
        MemberLevel max = memberLevelService.get(QueryBuilder.newBuilder().gt("experience", min.getExperience()).build());
        long experience = Long.MAX_VALUE;
        if (max != null) {
            experience = max.getExperience();
        }
        Query q1 = QueryBuilder.newBuilder().eq("experience", min.getExperience()).build();
        Query q2 = QueryBuilder.newBuilder().gt("experience", min.getExperience()).lt("experience", experience).build();
        return getMapper().page(SelectBuilder.newBuilder().addQuery(q1).addQuery(q2).build(), current, size);
    }
    
    public Page<Member> pageAscByUserId(Integer current, Integer size) {
        return super.pageAsc(current, size, "user_id");
    }
    
    @Override
    public int updateById(Object e, Object id) {
        if (e instanceof MemberUpdate) {
            MemberUpdate member = (MemberUpdate) e;
            if (IntegerUtils.isZero(member.getVipId())) {
                return getMapper().update(UpdateBuilder.newBuilder().setValue("experience", member.getExperience()).setNull("vip_id").setNull("expiration").addQuery(QueryBuilder.newBuilder().eq("id", id).build()).build());
            } else if (member.getExpiration() == null) {
                member.setExpiration(LocalDate.now().plusYears(99L));
            }
        }
        return super.updateById(e, id);
    }
    
}
